package com.ruoyi.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.pojo.ChatTable;
import com.ruoyi.service.ChatTableService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
    @RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatTableService chatTableService;
    @Autowired
    private ISysUserService iSysUserService;

    @GetMapping("/list")
    public R<List<SysUser>> list(@RequestParam Integer userid) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userid",userid);
        List<ChatTable> list = chatTableService.list(wrapper);
        List<SysUser> sysUsers = new ArrayList<SysUser>();
        for (ChatTable i:list) {
            Integer toid = i.getToid();
            SysUser sysUser = iSysUserService.selectUserById(toid.longValue());
            sysUsers.add(sysUser);
        }
        return R.success(sysUsers);
    }

    @PostMapping("/add")
    public R<String> add(@RequestBody ChatTable chatTable){
        int i = chatTableService.add(chatTable);
        ChatTable chatTable1 = new ChatTable();
        chatTable1.setToid(chatTable.getUserid());
        chatTable1.setUserid(chatTable.getToid());
        int i1 = chatTableService.add(chatTable1);
        if (i > 0) {
            return R.success("添加成功");
        }else {
            return R.error("添加失败");
        }
    }

    @GetMapping("/one")
    public R<ChatTable> one(ChatTable chatTable){
        QueryWrapper<ChatTable> wrapper = new QueryWrapper<>();
        wrapper.eq("userid",chatTable.getUserid());
        wrapper.eq("toid",chatTable.getToid());
        ChatTable one = chatTableService.getOne(wrapper);
        return R.success(one);
    }

    @DeleteMapping("/removetable")
    public R<Boolean> removeList(@RequestBody ChatTable chatTable){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("userid",chatTable.getUserid());
        wrapper.eq("toid",chatTable.getToid());
        wrapper.or();
        wrapper.eq("toid",chatTable.getUserid());
        wrapper.eq("userid",chatTable.getToid());
        boolean remove = chatTableService.remove(wrapper);
        return R.success(remove);
    }
}
